<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

namespace app\filters;

use app\models\UserLogin;
use Yii;
use yii\base\ActionEvent;
use yii\base\Behavior;
use yii\web\Controller;

class LoginFilter extends Behavior {

    public $actions = [];

    /**
     * Declares event handlers for the [[owner]]'s events.
     * @return array events (array keys) and the corresponding event handler methods (array values).
     */
    public function events() {
        return [Controller::EVENT_BEFORE_ACTION => 'beforeAction'];
    }

    /**
     * @param ActionEvent $event
     * @return boolean
     * @throws MethodNotAllowedHttpException when the request method is not allowed.
     */
    public function beforeAction($event) {
    
        if ($this->actions && !isset($this->actions[$event->action->actionMethod])) {
            return true;
        }

        // 判断登录状态
        if (!UserLogin::getIsLogined()) {
            if ($code = \Yii::$app->request->get('code')) {
                // 通过code获取信息
                UserLogin::checkAuth($code);
            } else {
                // 跳转自动获得code
                UserLogin::generateCode();
            }
        }

        return true;
    }
}
